package nina.yiyou.attendance.s10merge.compute

import groovy.transform.PackageScope
import nina.yiyou.attendance.s10merge.input.AttendLeaveExcelReader
import nina.yiyou.attendance.s10merge.input.AttendPunchExcelV2Reader

import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime

import static java.util.stream.Collectors.toList

@PackageScope
class PunchDayMaker {

  PunchDayMaker(LocalDate date, AttendDetailMerger.Employee employee, AttendPunchExcelV2Reader.Line dayLine, Set<String> extraArg, Map<String, List<AttendLeaveExcelReader.Line>> leaveMap) {
    _date = date
    _employee = employee
    _dayLine = dayLine
    _extraArg = extraArg
    _leaveMap = leaveMap
  }

  AttendDetailMerger.PunchDay make() {
    String employeeName = _employee.name()

    List leaveList = (_leaveMap[employeeName] ?: []).stream()
        .filter { it.startTime().toLocalDate() == _date }
        .collect(toList())

    return new AttendDetailMerger.PunchDay() {
      @Override
      AttendDetailMerger.Employee employee() {
        return _employee
      }

      @Override
      LocalDate date() {
        return _date
      }

      @Override
      LocalDateTime punchIn() {
        return _dayLine.punchIn()
      }

      @Override
      LocalDateTime punchOut() {
        return _dayLine.punchOut()
      }

      @Override
      double workingHour() {
        return _dayLine.workingHour()
      }

      @Override
      boolean isPunchFree() {
        return _extraArg.contains('免打卡')
      }

      @Override
      int forgotPunch() {
//        return _extraArg.contains('忘打卡') ? 1 : 0
        return _dayLine.forgotPunch()
      }

      @Override
      LocalTime overrideLatePoint() {
        return _extraArg.stream()
            .filter { it.startsWith('迟到线=') }
            .findAny()
            .map { it.split('=', 2)[1] }
            .map { LocalTime.parse(it) }
            .orElse(null)
      }

      @Override
      List<AttendLeaveExcelReader.Line> leaveList() {
        return leaveList
      }

      @Override
      String toString() {
        return "Day{${_date},${_employee.name()}}"
      }
    }
  }

  private final LocalDate _date
  private final AttendDetailMerger.Employee _employee

  private final AttendPunchExcelV2Reader.Line _dayLine
  private final Set<String> _extraArg

  private final Map<String, List<AttendLeaveExcelReader.Line>> _leaveMap
}
